package com.wannengbang.cloudleader.mine;


import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;
import com.wannengbang.cloudleader.R;
import com.wannengbang.cloudleader.base.BaseActivity;
import com.wannengbang.cloudleader.base.DataCallBack;
import com.wannengbang.cloudleader.bean.AddressListBean;
import com.wannengbang.cloudleader.bean.BaseResponseBean;
import com.wannengbang.cloudleader.bean.ExchangeListBean;
import com.wannengbang.cloudleader.bean.OrderDetailsBean;
import com.wannengbang.cloudleader.bean.OrderListBean;
import com.wannengbang.cloudleader.bean.PrepareConfigBean;
import com.wannengbang.cloudleader.bean.UserInfoBean;
import com.wannengbang.cloudleader.event.OrderRefushEvent;
import com.wannengbang.cloudleader.homepage.model.HomePageModelImpl;
import com.wannengbang.cloudleader.homepage.model.IHomePageModel;
import com.wannengbang.cloudleader.mine.adapter.OrderProductListAdapter;
import com.wannengbang.cloudleader.mine.model.IMineModel;
import com.wannengbang.cloudleader.mine.model.MineModelImpl;
import com.wannengbang.cloudleader.utils.DateTimeUtil;
import com.wannengbang.cloudleader.utils.NumberFormatUtils;
import com.wannengbang.cloudleader.utils.SPManager;
import com.wannengbang.cloudleader.utils.ToastUtil;
import com.wannengbang.cloudleader.widget.AppTitleBar;
import com.wannengbang.cloudleader.widget.CommonNoTitleDialog;
import com.wannengbang.cloudleader.widget.ViewLoading;
import com.wannengbang.cloudleader.widget.WrapContentLinearLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ByOrderDetailsActivity extends BaseActivity {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.tv_order_status)
    TextView tvOrderStatus;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_select_address)
    LinearLayout llSelectAddress;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;
    @BindView(R.id.tv_order_no)
    TextView tvOrderNo;
    @BindView(R.id.tv_copy)
    TextView tvCopy;
    @BindView(R.id.tv_create_time)
    TextView tvCreateTime;
    @BindView(R.id.tv_pay_time)
    TextView tvPayTime;
    @BindView(R.id.ll_pay_time)
    LinearLayout llPayTime;
    @BindView(R.id.tv_btn_delivery)
    TextView tvBtnDelivery;
    @BindView(R.id.tv_prepare_goods)
    TextView tvPrepareGoods;
    @BindView(R.id.tv_machines_no)
    TextView tvMachinesNo;
    @BindView(R.id.ll_machines_no)
    LinearLayout llMachinesNo;
    @BindView(R.id.tv_delivery_type)
    TextView tvDeliveryType;
    @BindView(R.id.ll_delivery_type)
    LinearLayout llDeliveryType;
    @BindView(R.id.tv_delivery_no)
    TextView tvDeliveryNo;
    @BindView(R.id.ll_delivery_no)
    LinearLayout llDeliveryNo;
    @BindView(R.id.tv_order_type)
    TextView tvOrderType;
    @BindView(R.id.tv_copy_no)
    TextView tvCopyNo;
    @BindView(R.id.tv_copy_machines)
    TextView tvCopyMachines;
    @BindView(R.id.ll_btn)
    LinearLayout llBtn;
    @BindView(R.id.tv_copy_address)
    TextView tvCopyAddress;
    @BindView(R.id.tv_turn_superior)
    TextView tvTurnSuperior;
    private OrderListBean.DataBean.ItemListBean dataBean;
    private IMineModel mineModel;
    private CommonNoTitleDialog.Builder dialogBuild;
    private String shop_order_id;
    private String select_type;
    private IHomePageModel homePageModel;
    private String[] deliverName = {"顺丰速运", "圆通速递", "中通快递", "申通快递", "韵达速递", "邮政包裹", "德邦快递", "百世快递", "天天快递"};
    private UserInfoBean userInfoBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_by_order_details);
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .statusBarDarkFont(false)
                .navigationBarDarkIcon(true)
                .navigationBarColor(R.color.white)
                .statusBarDarkFont(false, 0.2f)
                .init();
        registerEventBus();
        initView();
        requestOrderShow();
    }

    @Subscribe
    public void updata(OrderRefushEvent event) {
        requestOrderShow();
    }

    public void initView() {
        mineModel = new MineModelImpl();
        homePageModel = new HomePageModelImpl();
        shop_order_id = getIntent().getStringExtra("shop_order_id");
        select_type = getIntent().getStringExtra("select_type");
        userInfoBean = new Gson().fromJson(SPManager.getInstance().getUserInfoJson(), UserInfoBean.class);
    }

    public void requestOrderShow() {
        ViewLoading.showProgress(mActivity);
        mineModel.requestOrderShow(shop_order_id, select_type, new DataCallBack<OrderDetailsBean>() {
            @Override
            public void onSuccessful(OrderDetailsBean bean) {
                dataBean = bean.getData();
                if (dataBean != null) {
                    AddressListBean.DataBean.ItemListBean addressBean = dataBean.getAgent_address();
                    tvName.setText(addressBean.getName());
                    tvMobile.setText(addressBean.getMobile());
                    tvAddress.setText(addressBean.getProvince() + addressBean.getCity() + addressBean.getArea() + addressBean.getAddress());

                    tvBtnDelivery.setVisibility(View.GONE);
                    tvPrepareGoods.setVisibility(View.GONE);
                    tvTurnSuperior.setVisibility(View.GONE);
                    llBtn.setVisibility(View.GONE);
                    if (dataBean.getOrder_status() == 1) {
                        tvOrderStatus.setText("等待(" + dataBean.getAgent_name() + dataBean.getAgent_mobile() + ")付款");
                    } else if (dataBean.getOrder_status() == 2) {
                        tvOrderStatus.setText("待发货给(" + dataBean.getAgent_name() + dataBean.getAgent_mobile() + ")");
                        tvBtnDelivery.setVisibility(View.VISIBLE);
                        tvPrepareGoods.setVisibility(View.VISIBLE);
                        if (userInfoBean.getData().getId() != 1) {
                            tvTurnSuperior.setVisibility(View.VISIBLE);
                        }
                        llBtn.setVisibility(View.VISIBLE);
                    } else if (dataBean.getOrder_status() == 3) {
                        tvOrderStatus.setText("等待(" + dataBean.getAgent_name() + dataBean.getAgent_mobile() + ")收货");
                        //总账户
                        if (userInfoBean.getData().getId() == 1) {
                            if (dataBean.getShop_goods_count() - dataBean.getDelivery_goods_count() > 0) {
                                tvPrepareGoods.setVisibility(View.VISIBLE);
                                llBtn.setVisibility(View.VISIBLE);
                            }
                        }
                    } else if (dataBean.getOrder_status() == 4) {
                        tvOrderStatus.setText("已完成(" + dataBean.getAgent_name() + dataBean.getAgent_mobile() + ")");
                        //总账户
                        if (userInfoBean.getData().getId() == 1) {
                            if (dataBean.getShop_goods_count() - dataBean.getDelivery_goods_count() > 0) {
                                tvPrepareGoods.setVisibility(View.VISIBLE);
                                llBtn.setVisibility(View.VISIBLE);
                            }
                        }
                    } else if (dataBean.getOrder_status() == 9) {
                        tvOrderStatus.setText("已取消(" + dataBean.getAgent_name() + dataBean.getAgent_mobile() + ")");
                    }
                    if (dataBean.getDelivery_type() == 1) {
                        //1余额
                        if (dataBean.getIs_earnings() == 1) {
                            tvOrderType.setText("线上付款(账户余额支付)");
                        } else {
                            // 1微信 2支付宝
                            if (dataBean.getPay_type() == 1) {
                                tvOrderType.setText("线上付款(微信支付)");
                            } else if (dataBean.getPay_type() == 2) {
                                tvOrderType.setText("线上付款(支付宝支付)");
                            } else {
                                tvOrderType.setText("线上付款");
                            }
                        }

                    } else if (dataBean.getDelivery_type() == 2) {
                        tvOrderType.setText("线下付款");
                    } else {
                        tvOrderType.setText("");
                    }
                    String totalPrice = NumberFormatUtils.formatDouble(Double.parseDouble(dataBean.getOrder_fee()) / 100);
                    tvTotalPrice.setText(totalPrice);

                    OrderProductListAdapter listAdapter = new OrderProductListAdapter(dataBean.getShop_order_goods());
                    recyclerView.setLayoutManager(new WrapContentLinearLayoutManager(mActivity));
                    recyclerView.setAdapter(listAdapter);

                    tvCreateTime.setText(DateTimeUtil.format7(new Date(Long.parseLong(dataBean.getCreate_time()) * 1000)));
                    if (dataBean.getIs_pay() == 1 && !TextUtils.isEmpty(dataBean.getPay_time())) {
                        llPayTime.setVisibility(View.VISIBLE);
                        tvPayTime.setText(DateTimeUtil.format7(new Date(Long.parseLong(dataBean.getPay_time()) * 1000)));
                    } else {
                        llPayTime.setVisibility(View.GONE);
                    }
                    tvOrderNo.setText(dataBean.getId());
                    StringBuffer buffer = new StringBuffer();
                    if (dataBean.getDevice_group() != null && dataBean.getDevice_group().size() > 0) {
                        for (PrepareConfigBean.DataBean bean1 : dataBean.getDevice_group()) {
                            buffer.append(bean1.getStart_no() + "-" + bean1.getEnd_no() + "\n");
                        }
                        tvMachinesNo.setText(buffer);
                        llMachinesNo.setVisibility(View.VISIBLE);
                    } else {
                        llMachinesNo.setVisibility(View.GONE);
                    }
                    if ((dataBean.getConsign_delivery_type() > 0 && dataBean.getConsign_delivery_type() < 10) && !TextUtils.isEmpty(dataBean.getConsign_delivery_no())) {
                        llDeliveryType.setVisibility(View.VISIBLE);
                        llDeliveryNo.setVisibility(View.VISIBLE);
                        tvDeliveryType.setText(deliverName[dataBean.getConsign_delivery_type() - 1]);
                        tvDeliveryNo.setText(dataBean.getConsign_delivery_no());
                    } else {
                        llDeliveryType.setVisibility(View.GONE);
                        llDeliveryNo.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    public void requestAgentTurnParent(String order_no) {
        mineModel.requestAgentTurnParent(order_no, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort(bean.getMsg());
                EventBus.getDefault().post(new OrderRefushEvent());
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

    @OnClick({R.id.tv_copy_address, R.id.tv_copy, R.id.tv_turn_superior, R.id.tv_btn_delivery, R.id.tv_prepare_goods, R.id.tv_copy_no, R.id.tv_copy_machines})
    public void onViewClicked(View view) {
        if (dataBean == null) {
            return;
        }
        switch (view.getId()) {
            case R.id.tv_copy:
                //获取剪贴板管理器
                ClipboardManager cm = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label", dataBean.getId());
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                ToastUtil.showShort("复制成功");
                break;
            case R.id.tv_copy_no:
                //获取剪贴板管理器
                cm = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                mClipData = ClipData.newPlainText("Label", dataBean.getConsign_delivery_no());
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                ToastUtil.showShort("复制成功");
                break;
            case R.id.tv_copy_address:
                AddressListBean.DataBean.ItemListBean addressBean = dataBean.getAgent_address();
                if (addressBean == null) {
                    return;
                }
                String address = addressBean.getName() + " " + addressBean.getMobile() + " " + addressBean.getProvince() + addressBean.getCity() + addressBean.getArea() + addressBean.getAddress();
                //获取剪贴板管理器
                cm = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                mClipData = ClipData.newPlainText("Label", address);
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                ToastUtil.showShort("复制成功");
                break;
            case R.id.tv_copy_machines:
                //获取剪贴板管理器
                cm = (ClipboardManager) mActivity.getSystemService(Context.CLIPBOARD_SERVICE);
                // 创建普通字符型ClipData
                mClipData = ClipData.newPlainText("Label", tvMachinesNo.getText().toString());
                // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                ToastUtil.showShort("复制成功");
                break;
            case R.id.tv_turn_superior:
                String order_no = dataBean.getId();
                dialogBuild = new CommonNoTitleDialog.Builder(mActivity);
                dialogBuild.setMessage("是否转给上级发货?");
                dialogBuild.setPositiveButton("确定", v -> {
                    dialogBuild.dismiss();
                    requestAgentTurnParent(order_no);
                });
                dialogBuild.setNegativeButton("取消", v -> dialogBuild.dismiss());
                dialogBuild.setCancelable(false);
                dialogBuild.show();
                break;
            case R.id.tv_btn_delivery:
                order_no = dataBean.getId();
                Intent intent = new Intent(mActivity, SendDeliveryActivity.class);
                intent.putExtra("shop_order_id", order_no);
                startActivity(intent);
                break;
            case R.id.tv_prepare_goods:
                order_no = dataBean.getId();
                intent = new Intent(mActivity, PrepareGoodsActivity.class);
                intent.putExtra("shop_order_id", order_no);
                intent.putExtra("select_type", "delivery_by_me");
                startActivity(intent);
                break;

        }
    }
}
